package com.java1234.controller;

import com.java1234.entity.ExamQuestion;
import com.java1234.entity.R;
import com.java1234.service.ExamQuestionService;
import com.java1234.util.LogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 考试题目Controller
 */
@RestController
@RequestMapping("/bsns/subject/examQuestions")
public class ExamQuestionController {
    @Autowired private ExamQuestionService examQuestionService;

    @Autowired private LogUtil logUtil;

    /**
     * 查询所有考试题目信息
     */
    @GetMapping("/listAll")
    public R listAll(){
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("examQuestions",examQuestionService.list());
        return R.ok(resultMap);
    }

    /**
     * 批量添加考试题目
     * @param examQuestions 考试题目列表
     */
    @PostMapping("/add")
    public R add(@RequestBody List<ExamQuestion> examQuestions, HttpServletRequest request){
        boolean isSaved = examQuestionService.saveBatch(examQuestions);
        if(isSaved){
            logUtil.logOperation(request, "批量添加考试题目", "POST /bsns/subject/examQuestions/add", examQuestions.toString(), "成功");
            return R.ok("批量添加成功");
        }else{
            return R.error("批量添加失败");
        }
    }

    /**
     * 根据考试ID查询考试题目
     * @param id 考试ID
     */
    @GetMapping("/listByExaminationId/{id}")
    public R listByExaminationId(@PathVariable("id") Long id){
        List<ExamQuestion> examQuestions = examQuestionService.listByExaminationId(id);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("examQuestions", examQuestions);
        return R.ok(resultMap);
    }

    /**
     * 更新考试题目
     * @param examQuestion 考试题目对象
     */
    @PostMapping("/update")
    public R update(@RequestBody ExamQuestion examQuestion, HttpServletRequest request){
        boolean isUpdated=examQuestionService.updateById(examQuestion);
        if(isUpdated){
            logUtil.logOperation(request, "更新考试题目", "POST /bsns/subject/examQuestions/update", examQuestion.toString(), "成功");
            return R.ok("更新成功");
        }else{
            return R.error("更新失败");
        }
    }

    /**
     * 根据考试ID删除考试题目
     * @param params 考试ID
     */
    @PostMapping("/deleteByExaminationId")
    public R deleteByExaminationId(@RequestBody Map<String, Long> params, HttpServletRequest request) {
        Long examinationId = params.get("examinationId");
        boolean isDeleted = examQuestionService.removeByExaminationId(examinationId);
        if (isDeleted) {
            logUtil.logOperation(request, "根据考试ID删除考试题目", "POST /bsns/subject/examQuestions/deleteByExaminationId", params.toString(), "成功");
            return R.ok("删除成功");
        } else {
            return R.error("删除失败");
        }
    }

}
